package com.system.boot.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.system.boot.login.service.ApplyService;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.yang.common.core.exception.BaseException;
import org.yang.common.core.model.ApplyToken;
import org.yang.common.core.model.AuthDto;

import java.util.Base64;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

/**
 * @author: lslands
 * @description:
 * @version：v1.0
 * @date: 2024/6/6 15:59
 */
@Service
@RequiredArgsConstructor
public class ApplyServiceImpl implements ApplyService {
    private final LoadBalancerClient loadBalancerClient;
    private final RestTemplate restTemplate;

    private final static String SERVICE_NAME="sso-oauth2";
    private final static String TOKEN_URL="/oauth2/token";
    private final static String AUTHORIZATION="Authorization";
    private final static String GRANT_TYPE="password";


    @Override
    public ApplyToken applyToken(AuthDto dto) throws BaseException {
        //调用远程服务
        ServiceInstance instance = loadBalancerClient.choose(SERVICE_NAME);
        String url = "http://192.168.1.83:9110"+TOKEN_URL;
        LinkedMultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        String ht = getHttpBasic(dto.getClientId(),dto.getClientSecret());
        header.add(AUTHORIZATION,ht);
        //定义请求体 body
        LinkedMultiValueMap<String,String> body = new LinkedMultiValueMap<>();
        body.add("grant_type",Optional.ofNullable(dto.getGrantType()).orElse(GRANT_TYPE));
        body.add("username",Optional.ofNullable(dto.getUsername()).orElseThrow(BaseException::new));
        body.add("password", dto.getPassword());
        body.add("scope",dto.getScope());
        body.add("code",dto.getCode());

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body,header);
        ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST,httpEntity,Map.class);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void  handleError(@NotNull ClientHttpResponse response) throws IOException {
                super.handleError(response);
            }
        });
        Map map = Optional.ofNullable(exchange.getBody()).orElseThrow(BaseException::new);
        return  JSON.parseObject(JSON.toJSONString(map), ApplyToken.class);
    }



    /**
     * 获取httpbasic 的串
     * @param clinetId 客户端ID
     * @param clientSecret 客户端密钥
     * @return httpbasic串
     */
    private String getHttpBasic(String clinetId,String clientSecret){
        String string = clinetId+":"+clientSecret;
        String encoded = Base64.getEncoder().encodeToString(string.getBytes());
        return "Basic "+encoded;
    }
}
